package br.com.supermercado.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;

import br.com.supermercado.domain.Supermercado;

@Name("supermercadoDAO")
@AutoCreate
public class SupermercadoDAO {

	@In
	private Session hibernateSession;

	public Supermercado create(Supermercado supermercado) {
		hibernateSession.persist(supermercado);

		return supermercado;

	}

	public Supermercado update(Supermercado supermercado) {
		hibernateSession.merge(supermercado);

		return supermercado;

	}

	public void delete(Supermercado supermercado) {
		hibernateSession.delete(supermercado);

	}

	public Supermercado load(int id) {
		return (Supermercado) hibernateSession.get(Supermercado.class, id);

	}

	@SuppressWarnings("unchecked")
	public List<Supermercado> loadAll() {
		List<Supermercado> out = hibernateSession.createQuery("from Supermercado").list();

		return out;

	}

	public List<Supermercado> findByDescricao(String descricao) {
		Criteria criteria = hibernateSession.createCriteria(Supermercado.class);
		
		criteria.add(Restrictions.ilike("descricao", descricao, MatchMode.ANYWHERE));
		criteria.addOrder(Order.asc("descricao"));
		
		List<Supermercado> out = criteria.list();
		
		return out;
		
	}

	public Supermercado findByNome(String nomeSupermercado) {
		Criteria criteria = hibernateSession.createCriteria(Supermercado.class);
		
		criteria.add(Restrictions.eq("descricao", nomeSupermercado));
		
		Supermercado out = (Supermercado) criteria.uniqueResult();
		
		return out;

	}

}
